package common;


public class Encrypt {

    public final static int NO_ENCRYPTION = 0;
    public final static int ROT13_ENCRYPTION = 1;
    public final static int SWAP_ENCRYPTION = 2;
    private static int encryptMode = 2;

    public static void setEncryptMode(int mode) {
       encryptMode = mode;
    }

    /**
     * This function encrypt and decrypts messages based on the current
     * encryption mode.
     */
    public static TextMessage encrypt(TextMessage msg) {
        if (encryptMode == NO_ENCRYPTION) {
            return msg;
        } else if (encryptMode == ROT13_ENCRYPTION) {
            return encryptionRot13(msg);
        } else if (encryptMode == SWAP_ENCRYPTION) {
            return encryptionSwap(msg);
        } else {
            return msg;
        }
    }

    /**
     * Encodes a TextMessage using ROT13
     */
    public static TextMessage encryptionRot13(TextMessage msg) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < msg.getContent().length(); i++) {
            char current = msg.getContent().charAt(i);
            if ((current >= 'a' && current <= 'm')
                    || (current >= 'A' && current <= 'M')) {
                sb.append((char) (current + 13));
            } else if ((current >= 'n' && current <= 'z')
                    || (current >= 'N' && current <= 'Z')) {
                sb.append((char) (current - 13));
            } else {
                sb.append(current);
            }
        }
        return new TextMessage(sb.toString());
    }

    /**
     * Encodes a TextMessage by swapping the first two letters of each word
     */
    private static TextMessage encryptionSwap(TextMessage msg) {
        String result = "";
        String oldMessage = msg.getContent();
        if (oldMessage.length() > 2) {
            String firstLettersSwapped = oldMessage.substring(0, 2).replaceFirst
                    ("([\\w])([\\w])", "$2$1") + oldMessage.substring(2);
            result = firstLettersSwapped.replaceAll("(\\s)([\\w])([\\w])",
                    "$1$3$2");
        } else {
            result = oldMessage.replaceFirst("([\\w])([\\w])", "$2$1");
        }
        return new TextMessage(result);
    }

}
